package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.ParseException
import java.text.SimpleDateFormat;
import java.time.Instant

import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

import cn.com.kh.KHUtil;
import cn.com.kh.hst.ThreeDesUtil;
import cn.com.kh.getProperty;


/**
 *
 * @Title: aipHSTCustRegisterNameinfo
 * @Description:华盛证券 服务顾问 按照用户的华盛号查询客户注册后的一些信息 --内部接口
 * @author: cheih
 * @date 2022-05-20 22:00:00
 *
 */

public class aipHSTCustRegisterNameinfo implements ServiceBackInvoke {
	private static final Log log = LogFactory.getLog(aipHSTCustRegisterNameinfo.class);

	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");

		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";
		String outData = "";
		String dataSourceID = "dataSource";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}

		try {

			long startTime = System.currentTimeMillis();
			String reJson = null;
			long endTime = 0;

			// 调用处理信息
			JSONObject inObject = new JSONObject(inData);
			log.debug("处理前的Json：" + inObject.toString());
			
			//鉴权变量
			String appid = getProperty.get("appid");
			String appsecret = getProperty.get("appsecret");

			//sign加密前后
			String signfront = "";
			String signafter = "";
			
			def token = "";
			def hsNo ="";
			def remoteAddr = "";
			def customer_id="";
			
			//String getcustSQL = "select  a.customer_id from (select customer_id from  customer where  customername is null UNION select customer_id from  customer where  customername ='' UNION select customer_id from  customer where  customername ='匿名') a order by cast(customer_id as SIGNED) desc LIMIT 0,20000";
			//String getcustSQL = "select  a.customer_id from (select customer_id,CREATEDDATE from  customer where  Stringfield13 is null UNION select customer_id,CREATEDDATE from  customer where  Stringfield13 ='') a where  a.customer_id is not null  and a.customer_id>100 order by CREATEDDATE,cast(a.customer_id as SIGNED) desc";
			
			String getcustSQL = "select  a.customer_id from (select customer_id,CREATEDDATE from  customer where  sq_9 is null UNION select customer_id,CREATEDDATE from  customer where  sq_9 ='') a where  a.customer_id is not null  and a.customer_id>100  order by cast(a.customer_id as SIGNED) desc";
			//and a.customer_id='3065137'
			
			//String getcustSQL = "select customer_id from  customer where  customername is null limit 10";
			List getcustList = eliteBean.chaxun_sql(getcustSQL, "dataSource");
			
			if(getcustList.size()>0){
				
				for (int i = 0; i <getcustList.size(); i++) {
					
					def getStringfield2result = eliteBean.chaxun_sql("select HOUR(timediff(NOW(),Stringfield2))*60 + MINUTE(timediff(NOW(),Stringfield2)) + SECOND(timediff(NOW(),Stringfield2))/60 as Stringfield,STRINGFIELD1,LOGINNAME from  staff where STAFF_ID='000221'", "dataSource");
					
					def Stringfield=getStringfield2result.get(0).get("Stringfield");
					def LOGINNAME=getStringfield2result.get(0).get("LOGINNAME");
					def STRINGFIELD1=getStringfield2result.get(0).get("STRINGFIELD1");
					
					if(Stringfield>=30){
						token=Loginin(LOGINNAME);
					}else{
						token=STRINGFIELD1;
					}

					//华盛接口连续调用可能异常 添加2S睡眠
					Thread.sleep(1 * 1000);
					Map getcustMap = getcustList.get(i);
					hsNo = getcustMap.get("customer_id");
					log.debug("当前客户-" + "hsNo: " + hsNo);
					
					String sign_time=Instant.now().getEpochSecond();
					log.debug("解析信息-" + "sign_time: " + sign_time);

					HashMap<String, String> paramHashMap = new HashMap<String, String>();
					paramHashMap.put("token", token);
					paramHashMap.put("sign_time", sign_time);
					if(hsNo!=''&&hsNo!=null&&hsNo!="undefined") {
						paramHashMap.put("hsNo", hsNo);
					}

					log.debug("paramHashMap：" + paramHashMap);
					//自然排序 升序参数
					signfront= ThreeDesUtil.sortMap(paramHashMap,appid,appsecret);
					log.debug("sign加密MD5前：" + signfront);
					signafter = Util.getMD5Str(signfront);
					log.debug("sign加密MD5后：" + signafter);

					//拼接接口入参
					paramHashMap.put("client_key", appid);
					paramHashMap.put("sign", signafter);

					String injson=ThreeDesUtil.SplicingMap(paramHashMap,"&");
					log.debug("injson:" + injson);

					outData = getcust(eliteBean, injson,dataSourceID);
				}
	
			}

		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			outData = "{\"result\":\"-1\",\"message\":\"接口查询失败(" + e.getMessage() + ")\",\"data\":[]}";
		}
		log.debug("处理完成返回结果:" + outData);

		return outData;
	}

	//getcust
	public static String getcust(EliteBean eliteBean , String injson, String dataSourceID) {

		long startTime = System.currentTimeMillis();
		log.debug("处理开始时间:" + startTime);

		long endTime = System.currentTimeMillis();

		String reJson = null;
		try {
			String doURL = getProperty.get("HSTURL");
			doURL = doURL+"/ae/query-register-info";
			log.debug("doURL:" + doURL);

			Map<String, String> headMap = new HashMap<String, String>();
			headMap.put("Content-Type", "application/x-www-form-urlencoded");
			def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
			log.debug("getResult:" + getResult);

			//解析SSO返回信息
			JSONObject jsonObject = new JSONObject(getResult);
			String code = GetJV(jsonObject, "code");
			String result = GetJV(jsonObject, "result");

			JSONObject dataObject;
			log.debug("code:" + code);
			if(code == "00000") {
				dataObject = new JSONObject(result);
				String registerstatus = GetJV(dataObject, "registerstatus");//1已开户 2（注册） 3（暂存） 4（审核中）
				String customerid = GetJV(dataObject, "customerid");//华盛号
				String customername = GetJV(dataObject, "customername");//姓名
				String phone = GetJV(dataObject, "phone");//手机号
				String register = GetJV(dataObject, "register");//注册渠道
				String register_id = GetJV(dataObject, "register_id");//注册渠道ID
				String registertime = GetJV(dataObject, "registertime");//注册时间
				String stashtime = GetJV(dataObject, "stashtime");//暂存时间
				String audittime = GetJV(dataObject, "audittime");//审核时间
				String invitertype = GetJV(dataObject, "invitertype");//邀请类型
				String inviterhstno = GetJV(dataObject, "inviterhstno");//邀请人华盛号
				String invitername = GetJV(dataObject, "invitername");//邀请人姓名
								
				if(registertime!=""){
					registertime="'"+registertime+"'";
				}else{
					registertime=null;
				}
				if(stashtime!=""){
					stashtime="'"+stashtime+"'";
				}else{
					stashtime=null;
				}
				if(audittime!=""){
					audittime="'"+audittime+"'";
				}else{
					audittime=null;
				}
						
				def dataresult = eliteBean.update("insert into custregistertokenhis (customerid, customername, phone, register, register_id, registertime, stashtime,audittime,invitertype,inviterhstno,invitername,registerstatus,createtime) VALUES ('"+customerid+"','"+customername+"','"+phone+"','"+register+"','"+register_id+"',"+registertime+","+stashtime+","+audittime+",'"+invitertype+"','"+inviterhstno+"','"+invitername+"','"+registerstatus+"',now())", "dataSource");
				
				reJson = "{\"result\":\"1\",\"message\":"+ result +"}";
			}else if(code == "20003"){
				String msg = GetJV(jsonObject, "msg");
				reJson = "{\"result\":\"20003\",\"message\":\"查询客户注册后信息获取失败(" + msg + ")\"}";
			}else {
				String msg = GetJV(jsonObject, "msg");
				reJson = "{\"result\":\"-1\",\"message\":\"查询客户注册后信息获取失败(" + msg + ")\"}";
			}

		} catch (JSONException e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			reJson = "{\"result\":\"-1\",\"message\":\"查询客户注册后信息获取接口异常\"}";
		}

		return reJson;
	}

	//Loginin
	public static String Loginin(String loginname) {
		
		JSONObject bodyJson = new JSONObject();
		bodyJson.put("loginname", loginname);
		
		Map<String, String> headMap = new HashMap<String, String>();
		headMap.put("Content-Type", "application/json");
		def sysurl = "http://127.0.0.1:8080/EliteGeneralHttpTask/GeneralService/aipHSTHandLogin";
		def getResult = Util.doHttpPostUseHead(sysurl,bodyJson.toString(),"UTF-8",10000,0,headMap);
		log.debug("getResult:" + getResult);

		//解析返回信息
		JSONObject jsonObject = new JSONObject(getResult);
		String result = GetJV(jsonObject, "result");
		String token="";
		if(result=="1"){
			token = GetJV(jsonObject, "token");
		}
		return token;
	}

	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		log.debug("解析-k=" + getKey + " v=" + Rev_Value);
		return Rev_Value;
	}


	// 非空校验isNull
	public static boolean isNull(String value) {

		boolean reFlag = true;
		if (value == "" || value.length() <= 0) {
			reFlag = true;
		} else {
			reFlag = false;
		}
		log.debug(reFlag);
		return reFlag;
	}

	// 非空校验isNullMSG
	public static String isNullMSG(String key, String value) {

		String reResult = "";
		if (value == "" || value.length() <= 0) {
			reResult = key + "必填字段;";
		}
		return reResult;
	}

}
